const DRAWING_ITEMS = 'DrawingItems'
const DRAWING_ITEMS_VERSION = '1.4.29'
const DRAWING_ITEMS_VERSION_KEY = 'DRAWING_ITEMS_VERSION'
const DRAWING_ID = 'idGlobal'
const TREE_NODE_ID = 'treeNodeId'
const FORM_CONF = 'formConf'
import {parse,stringify} from './json.js'

function checkVersion(options){
  // 加入缓存版本的概念，保证缓存数据与程序匹配
  const version = localStorage.getItem(DRAWING_ITEMS_VERSION_KEY)
  if (version !== DRAWING_ITEMS_VERSION) {
    localStorage.setItem(DRAWING_ITEMS_VERSION_KEY, DRAWING_ITEMS_VERSION)
    clearDrawingList()
    return false
  }
  return true
}
function getSaveName({state,type}){
  return state+DRAWING_ITEMS
}

export function getDrawingList(options) {
  if(!checkVersion(options)) return
  const str = localStorage.getItem(getSaveName(options))
  if (str) return parse(str)
  return null
}

export function clearDrawingList() {
  localStorage.setItem(getSaveName({state: 'add'}), stringify([]))
  localStorage.setItem(getSaveName({state: 'edit'}), stringify([]))
}
export function saveDrawingList({state,type,list}) {
  // console.log('--saveDrawingList--')
  // console.log('name', getSaveName({state}))
  // console.log('list', list)
  localStorage.setItem(getSaveName({state}), stringify(list))
}

export function getIdGlobal() {
  const str = localStorage.getItem(DRAWING_ID)
  if (str) return parseInt(str, 10)
  return 100
}

export function saveIdGlobal(id) {
  localStorage.setItem(DRAWING_ID, `${id}`)
}

export function getTreeNodeId() {
  const str = localStorage.getItem(TREE_NODE_ID)
  if (str) return parseInt(str, 10)
  return 100
}

export function saveTreeNodeId(id) {
  localStorage.setItem(TREE_NODE_ID, `${id}`)
}

export function getFormConf() {
  const str = localStorage.getItem(FORM_CONF)
  if (str) return parse(str)
  return null
}

export function saveFormConf(obj) {
  localStorage.setItem(FORM_CONF, stringify(obj))
}
